package com.bdqn.ch02.sl;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class XMLParse {
    Document doc=null;
    public void getDocument(){
        //获取DOM树
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //获取解析器工厂
        try {
            DocumentBuilder builder=factory.newDocumentBuilder();
            //加载DOM树
            doc=builder.parse("src/dao/PhoneInfo.xml");
        } catch (ParserConfigurationException e) {
            e.fillInStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }
    public void showInfo(){
        //获取<Brand>的所有节点集合
        NodeList nodeList=doc.getElementsByTagName("Brand");
        for(int i=0;i<nodeList.getLength();i++){
            //从i=0时得到第一个节点开始
            Node brand=nodeList.item(i);
            Element brandEle=(Element)brand;
            //读取此节点的name属性:<Brand name="name">
            String brandStr=brandEle.getAttribute("name");
            NodeList types=brandEle.getChildNodes();
            for(int j=0;j<types.getLength();j++){
                //得到Brand下的第一个子节点
                Node type=types.item(j);
                if(type.getNodeType()==Node.ELEMENT_NODE){
                    Element typeEle=(Element)type;
                    String typeStr=typeEle.getAttribute("name");
                    System.out.println("手机:"+brandStr+typeStr);
                }
            }

        }

    }

    public static void main(String[] args) {
        XMLParse Parse=new XMLParse();
        Parse.getDocument();
        Parse.showInfo();
    }
}
